package cmd

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"
	"time"

	"github.com/louloulin/dataflare/pkg/devenv"
	"github.com/spf13/cobra"
)

var (
	workflowDir string
	hotReload   bool
	debugMode   bool
)

// devCmd represents the dev command
var devCmd = &cobra.Command{
	Use:   "dev",
	Short: "Start a local development environment",
	Long: `Start a local development environment for DataFlare workflows.

This command starts a local development environment that can deploy and run
workflows from a directory. It supports hot reload, which automatically
redeploys workflows when they are modified.

Example:
  dataflare dev --dir ./workflows --hot-reload`,
	RunE: func(cmd *cobra.Command, args []string) error {
		// Create logger
		logger := log.New(os.Stdout, "[DataFlare Dev] ", log.LstdFlags)

		// Create options
		options := []devenv.LocalRuntimeOption{
			devenv.WithWorkflowDir(workflowDir),
			devenv.WithHotReload(hotReload),
			devenv.WithLogger(logger),
		}

		// Create local runtime
		runtime, err := devenv.NewLocalRuntime(options...)
		if err != nil {
			return fmt.Errorf("failed to create local runtime: %w", err)
		}

		// Start local runtime
		if err := runtime.Start(); err != nil {
			return fmt.Errorf("failed to start local runtime: %w", err)
		}
		defer runtime.Stop()

		// Print info
		fmt.Printf("DataFlare local development environment started\n")
		fmt.Printf("Workflow directory: %s\n", workflowDir)
		fmt.Printf("Hot reload: %v\n", hotReload)
		fmt.Printf("Debug mode: %v\n", debugMode)

		// List deployed workflows
		workflows := runtime.ListWorkflows()
		if len(workflows) > 0 {
			fmt.Printf("Deployed workflows:\n")
			for _, workflow := range workflows {
				fmt.Printf("  - %s\n", workflow)
			}
		} else {
			fmt.Printf("No workflows deployed\n")
		}

		// Start debug session if debug mode is enabled
		var debugSession *devenv.DebugSession
		if debugMode && len(workflows) > 0 {
			// Create debug session for the first workflow
			debugSession, err = devenv.NewDebugSession(runtime, workflows[0])
			if err != nil {
				return fmt.Errorf("failed to create debug session: %w", err)
			}

			// Start debug session
			if err := debugSession.Start(); err != nil {
				return fmt.Errorf("failed to start debug session: %w", err)
			}
			defer debugSession.Stop()

			// Add debug points for all components
			for _, workflow := range workflows {
				// Get workflow ID
				workflowID, ok := runtime.DeployedWorkflows[workflow]
				if !ok {
					continue
				}

				// Get workflow definition
				definition, err := runtime.GetEngine().GetWorkflowDefinition(workflowID)
				if err != nil {
					continue
				}

				// Add debug points for sources
				for sourceID := range definition.Sources {
					debugSession.AddDebugPoint(&devenv.DebugPoint{
						Type:        "source",
						ComponentID: sourceID,
						Enabled:     true,
					})
				}

				// Add debug points for processors
				for processorID := range definition.Processors {
					debugSession.AddDebugPoint(&devenv.DebugPoint{
						Type:        "processor",
						ComponentID: processorID,
						Enabled:     true,
					})
				}

				// Add debug points for sinks
				for sinkID := range definition.Sinks {
					debugSession.AddDebugPoint(&devenv.DebugPoint{
						Type:        "sink",
						ComponentID: sinkID,
						Enabled:     true,
					})
				}
			}

			// Export debug data periodically
			go func() {
				ticker := time.NewTicker(30 * time.Second)
				defer ticker.Stop()

				for {
					select {
					case <-ticker.C:
						// Export debug data
						debugDataDir := filepath.Join(workflowDir, "debug")
						if err := os.MkdirAll(debugDataDir, 0755); err != nil {
							logger.Printf("Failed to create debug data directory: %v", err)
							continue
						}

						debugDataFile := filepath.Join(debugDataDir, fmt.Sprintf("debug_%s.json", time.Now().Format("20060102_150405")))
						if err := debugSession.ExportDebugData(debugDataFile); err != nil {
							logger.Printf("Failed to export debug data: %v", err)
						}
					}
				}
			}()
		}

		// Wait for signal
		sigCh := make(chan os.Signal, 1)
		signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
		<-sigCh

		fmt.Printf("Stopping DataFlare local development environment...\n")

		return nil
	},
}

func init() {
	rootCmd.AddCommand(devCmd)

	// Add flags
	devCmd.Flags().StringVarP(&workflowDir, "dir", "d", "./workflows", "Directory containing workflow definitions")
	devCmd.Flags().BoolVarP(&hotReload, "hot-reload", "r", false, "Enable hot reload")
	devCmd.Flags().BoolVarP(&debugMode, "debug", "g", false, "Enable debug mode")
}
